package com.whats.indicator.service.di;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class BusCenterTokenService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BusCenterTokenService.class);
    @Value("${outter.data.buscenter-token-url}")
    private String buscenterUrl;
    @Value("${outter.data.buscenter-clientid}")
    private String buscenterClientId;
    @Value("${outter.data.buscenter-clientsecret}")
    private String buscenterClientSecret;

    public String getToken() {
        LOGGER.info("======getToken url {}, id {}", buscenterUrl, buscenterClientId);

        // 请求参数
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("password", "");
        jsonParam.put("username", "");
        jsonParam.put("grant_type", "client_credentials");
        jsonParam.put("client_secret", buscenterClientSecret);
        jsonParam.put("client_id", buscenterClientId);

        try {
            // 发送POST请求
            String response = HttpUtil.createPost(buscenterUrl)
                    .body(jsonParam.toString()) // 设置请求体
                    .contentType("application/json") // 设置Content-Type
                    .execute()
                    .body(); // 获取响应内容

            LOGGER.info("======getToken response {}", response);
            if (StrUtil.isNotEmpty(response)) {
                JSONObject resultObj = JSONUtil.parseObj(response);
                if (StrUtil.isNotEmpty(resultObj.getStr("access_token"))) {
                    return resultObj.getStr("access_token");
                }
            }
        } catch (Exception e) {
            LOGGER.error("======getToken err", e);
        }
        return "";
    }
}
